import { createRouter, createWebHistory, Router, RouteRecordRaw } from 'vue-router';

import { IMenu } from '@/models/menu.interface';
import Layout from '@/views/layout.vue';
import Home from '@/views/home/index.vue';
import { routerGuard, statusGuard } from './router.guard';

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    component: Layout,
    children: [{
      path: '/home',
      name: 'home',
      component: Home,
    }],
  },
];

export const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

export function resetRouter() {
  router.getRoutes().forEach(route => {
    const { name } = route;
    if (name && router.hasRoute(name)) {
      router.removeRoute(name);
    }
  });
}

export const formatRouters = (menus: IMenu[] = [], router: Router) => {
  menus?.forEach(menu => {
    if (menu.menuPath) {
      const path = menu.menuUrl.startsWith('/') ? menu.menuUrl : `/${menu.menuUrl}`;
      router.addRoute('home', {
        path,
        name: menu.id.toString(),
        meta: { ...menu },
        component: () => import(`../views/${menu.menuPath}.vue`),
      });
    }
  });
};

routerGuard(router);
statusGuard(router);
